package org.goodev.arch;

import android.arch.lifecycle.LifecycleActivity;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;


public class LiveDataActivity extends LifecycleActivity {
    private TextView mTextView;
    private TextView mCountryTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.text);
        mCountryTV = (TextView) findViewById(R.id.country);

//        Util.checkUserStatus(result -> {
//            if (result) {
//                LocationLiveData.getsIns(this).observe(this, location -> {
//                    // update UI
//                    mTextView.setText(location.getLatitude() + ", " + location.getLongitude());
//                });
//            }
//        });

        demoTransformation();
    }

    private void demoTransformation() {
        LocationLiveData data = LocationLiveData.getsIns(this);
        LiveData<String> stringLatLon = Transformations.map(data,
                location -> location.getLatitude() + ", " + location.getLongitude());
        stringLatLon.observe(this, latLon -> {
            mTextView.setText(latLon);
        });

        Transformations.switchMap(data, location -> getCountryName(location))
            .observe(this, country -> mCountryTV.setText(country));
    }

    // 返回当前位置所在的国家名字
    private LiveData<String> getCountryName(Location loc) {
        // 只是为了演示，实际中需要把转换的逻辑封装到自定义的 LiveData 中，
        // 和 LocationLiveData 类似
        MutableLiveData<String> ld = new MutableLiveData<>();
        ld.postValue("中国");
        return ld;
    }

}
